package com.xhwl.centiotdata.integration.parkingguidance.keytop;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.integrator.KeytopIntegrationHandler;
import com.xhwl.centiotdata.integration.parkingguidance.ParkingGuidanceIntegrationConfig;
import com.xhwl.centiotdata.integration.parkingguidance.ParkingGuidanceSystemHandler;
import com.xhwl.centiotdata.integrator.parkingguidance.ParkingGuidanceRequestsDTO;
import com.xhwl.centiotdata.integrator.parkingguidance.ParkingGuidanceResponseDTO;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.enums.device.DeviceOnlineStatusEnum;
import com.xhwl.common.utils.ChkUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Falcon.cao @Copyright (C), 2022, 兴海物联
 * Date: 2022/10/5 9:54
 * Description: 科拓车位引导系统处理器
 */
@Slf4j
public class KeytopParkingGuidanceHandler extends KeytopIntegrationHandler implements ParkingGuidanceSystemHandler {

    private static final String OPEN_API_V1 = "/v1/open/";

    private static final String PATH_SPACE_INFO = "getSpaceInfo";       // 获取楼层车位情况
    private static final String PATH_AREAS_LIST = "getAreaList";        // 获取区域列表
    private static final String PATH_FLOOR_LIST = "getFloorList";       // 获取楼层列表
    private static final String PATH_FREE_SPACE_COUNT = "getFreeSpaceNum";      // 获取楼层区域空闲车位数量
    private static final Integer AREA_ID_ALL = -1;

    @Override
    public List<ParkingGuidanceResponseDTO> onListingParkerFloor(ParkingGuidanceIntegrationConfig config, ParkingGuidanceRequestsDTO request) {
        String response = execute(config, PATH_FLOOR_LIST, OPEN_API_V1, new JSONObject());
        JSONObject json = parse(response);
        if (json.isEmpty()) {
            return Collections.emptyList();
        }
        JSONArray array = json.getJSONArray("content");
        return array.toJavaList(ParkingGuidanceResponseDTO.class);
    }

    @Override
    public List<ParkingGuidanceResponseDTO> onListingParkingArea(ParkingGuidanceIntegrationConfig config, ParkingGuidanceRequestsDTO request) {
        JSONObject data = new JSONObject();
        data.put("floorId", request.getFloorId());
        String response = execute(config, PATH_AREAS_LIST, OPEN_API_V1, data);

        JSONObject json = parse(response);
        if (json.isEmpty()) {
            return Collections.emptyList();
        }

        JSONArray array = json.getJSONArray("content");
        return array.toJavaList(ParkingGuidanceResponseDTO.class);
    }

    @Override
    public List<ParkingGuidanceResponseDTO> onListingSpaceStatus(ParkingGuidanceIntegrationConfig config, ParkingGuidanceRequestsDTO request) {
        if (ChkUtil.isNull(request.getFloorId())) {
            List<ParkingGuidanceResponseDTO> bos = onListingParkerFloor(config, request);
            if (ChkUtil.isNull(bos)) {
                return Collections.emptyList();
            }
            List<ParkingGuidanceResponseDTO> results = new LinkedList<>();
            for (ParkingGuidanceResponseDTO dto : bos) {
                results.addAll(onListFloorSpaceStatus(config, Integer.parseInt(dto.getFloorId()), request.getAreaId()));
            }
            return results;
        }
        return onListFloorSpaceStatus(config, request.getFloorId(), request.getAreaId());
    }

    /**
     * 按楼层查询车位状态 （科拓不支持全量查询，只能按楼层依次查出）
     *
     * @param config  配置实体
     * @param floorId 楼层
     * @param areaId  区域
     */
    private List<ParkingGuidanceResponseDTO> onListFloorSpaceStatus(ParkingGuidanceIntegrationConfig config, Integer floorId, Integer areaId) {
        JSONObject data = new JSONObject();
        data.put("areaId", areaId);
        data.put("floorId", floorId);
        String response = execute(config, PATH_SPACE_INFO, OPEN_API_V1, data);

        JSONObject json = parse(response);
        if (json.isEmpty()) {
            return Collections.emptyList();
        }

        JSONArray array = json.getJSONArray("content");
        return array.toJavaList(ParkingGuidanceResponseDTO.class);
    }

    @Override
    public List<ParkingGuidanceResponseDTO> onListSpaceFreeCount(ParkingGuidanceIntegrationConfig config, ParkingGuidanceRequestsDTO request) {
        JSONObject data = new JSONObject();
        data.put("areaId", request.getAreaId());
        data.put("floorId", request.getFloorId());
        String response = execute(config, PATH_FREE_SPACE_COUNT, OPEN_API_V1, data);

        JSONObject json = parse(response);
        if (json.isEmpty()) {
            return Collections.emptyList();
        }

        JSONArray array = json.getJSONArray("content");
        return array.toJavaList(ParkingGuidanceResponseDTO.class);
    }

    @Override
    public ParkingGuidanceResponseDTO onGettingSpaceStatus(ParkingGuidanceIntegrationConfig config, ParkingGuidanceRequestsDTO request) {
        List<ParkingGuidanceResponseDTO> dtos = onListingSpaceStatus(config, request);
        for (ParkingGuidanceResponseDTO dto : dtos) {
            if (StringUtils.equals(dto.getSpaceNo(), request.getParkNo())) {
                ParkingGuidanceResponseDTO target = new ParkingGuidanceResponseDTO();
                target.setStatus(dto.getStatus());
                return target;
            }
        }
        return null;
    }

    @Override
    public List<DeviceDTO> onGetSpaceForDevice(ParkingGuidanceIntegrationConfig config) {
        ParkingGuidanceRequestsDTO parkingGuidanceRequestsDTO = new ParkingGuidanceRequestsDTO();
        parkingGuidanceRequestsDTO.setProjectId(config.getProjectId());
        parkingGuidanceRequestsDTO.setAreaId(AREA_ID_ALL);
        List<ParkingGuidanceResponseDTO> parkingGuidanceResponseDTOS = this.onListingSpaceStatus(config, parkingGuidanceRequestsDTO);
        //处理科拓-引导系统返回的设备信息，并将其封装为中台的设备实体类
        List<DeviceDTO> deviceDTOS = this.handleDeviceData(config, parkingGuidanceResponseDTOS);
        return deviceDTOS;
    }

    /**
     * 处理科拓地磁的车位信息，使其转换为中台的设备信息
     */
    private List<DeviceDTO> handleDeviceData(ParkingGuidanceIntegrationConfig config, List<ParkingGuidanceResponseDTO> parkingGuidanceResponseDTOS){
        log.info("科拓引导系统的配置为：{}",JSONObject.toJSONString(config));
        List<DeviceDTO> deviceDTOS = new LinkedList<>();
        for (ParkingGuidanceResponseDTO parkingGuidanceResponseDTO : parkingGuidanceResponseDTOS) {
            DeviceDTO deviceDTO = new DeviceDTO();
            deviceDTO.setProjectId(config.getProjectId());
            deviceDTO.setProductId(config.getProductId());
            deviceDTO.setDeviceTypeId(config.getDeviceType());
            deviceDTO.setCategoryId(config.getProdCategoryId());
            deviceDTO.setName(parkingGuidanceResponseDTO.getSpaceNo());
            deviceDTO.setThirdDeviceId(parkingGuidanceResponseDTO.getSpaceNo());
            deviceDTO.setOnlineStatus(this.convertKeTopDeviceStatus(parkingGuidanceResponseDTO.getStatus()));
            deviceDTOS.add(deviceDTO);
        }
        return deviceDTOS;
    }

    /**
     * 根据科拓地磁提供的接口文档中的地磁状态码来判断是否在离线
     */
    private Integer convertKeTopDeviceStatus(Integer status){
        switch (status){
            case 0:
            case 1:
                return DeviceOnlineStatusEnum.ONLINE.getId();
            default:
                return DeviceOnlineStatusEnum.OFFLINE.getId();
        }
    }
}
